const { 
  remote: { 
    Menu, 
    getCurrentWindow, 
    dialog, 
    globalShortcut
  }, 
  shell,
  ipcRenderer
} = require('electron')

const fs = require('fs')

const template = [
  {
    label: '复制'
  },
  {
    label: '粘贴'
  }
]
const menu = Menu.buildFromTemplate(template)
window.addEventListener('contextmenu', () => {
  // 将菜单添加到当前窗口
  menu.popup({
    window: getCurrentWindow()
  })
})

const a1 = document.getElementById('a1')
a1.onclick = function (e) {
  e.preventDefault()
  const url = this.getAttribute('href')
  shell.openExternal(url)
}


// 拖拽文件进行读取
const dragEl = document.querySelector('.drag')

dragEl.addEventListener('drop', (e) => {

  if(e.dataTransfer.files.length === 1) {
    const filePath = e.dataTransfer.files[0].path
    const fileContent = fs.readFileSync(filePath,'utf-8').toString()
    dragEl.innerText = fileContent
  }
})

dragEl.addEventListener('dragover', (e) => {
  e.preventDefault()
})


// 打开对话框 读取文件
function openFileDialog() {
  const res = dialog.showOpenDialogSync({
    title: '哈哈哈选择文件',
    buttonLabel: '读取',
    filters: [
      { name: 'Custom File Type', extensions: ['html','css','js'] }
    ]
  })

  if(res === undefined) return 
  const filePath = res[0]
  const fileContent = fs.readFileSync(filePath,'utf-8').toString()
  dragEl.innerText = fileContent
}

// 保存文件
function saveFileDialog () {
  const res = dialog.showSaveDialogSync({
    title: '保存文件',
    buttonLabel: '保存',
    filters: [
      { name: 'Custom File Type', extensions: ['js'] }
    ]
  })
  if(res === undefined) return 
  fs.writeFileSync(res, document.querySelector('#editValue').value)
}

// 提示消息
function showMsg () {
  dialog.showMessageBoxSync({
    type: 'warning',
    buttons: ['确定','取消'],
    title: '提示',
    message: '锄禾日当午，汗滴禾下土'
  })
}

// 最小窗口
function minWindow () {
  ipcRenderer.send('min-window')
}

// 最大窗口
let windowSize = 'min'
function maxWindow () {
  windowSize = windowSize === 'min' ? 'max':'min'
  ipcRenderer.send('max-window',windowSize)
}

// 关闭窗口
function closeWindow () {
  ipcRenderer.send('close-window')
}

async function getMsg () {
  const res =  await fetch('http://127.0.0.1:3006/api/person').then(res=>res.json())
  console.log(res)
}
